<?php

/**
 * LoginForm class.
 * LoginForm is the data structure for keeping
 * user login form data. It is used by the 'login' action of 'UserController'.
 */
Yii::import('application.modules.user.components.UserIdentity');


class AutoLoginUserIdentity extends UserIdentity {
    
    public function __construct($username="", $password="") {
        parent::__construct($username, $password);
    }
    
    public function authenticate() {
        
        session_start();
        $autoId = $_SESSION["AUTOLOGIN_USER_ID"];
        $user = User::model()->findByPk($autoId);
        
        if ($user) {
            $this->id = $user->id;
            $this->setState('id', $user->id);
            $this->username = $user->username;
            $this->errorCode = self::ERROR_NONE;
        } else {
            $this->errorCode = self::ERROR_USERNAME_INVALID;
        }
        return !$this->errorCode;
    }

}


class AutoLoginUser extends UserLogin {
    /**
     * Declares the validation rules.
     * The rules state that username and password are required,
     * and password needs to be authenticated.
     */
//    public function rules() {
//        return array(
//            // username and password are required
//            array('username, password', 'required'),
//            // rememberMe needs to be a boolean
//            // password needs to be authenticated
//            array('password', 'authenticate'),
//        );
//    }

    /**
     * Authenticates the password.
     * This is the 'authenticate' validator as declared in rules().
     */
    public function authenticate($attribute, $params) {


        if (!$this->hasErrors()) {  // we only want to authenticate when no input errors
            $identity = new AutoLoginUserIdentity();
            $identity->authenticate();

            switch ($identity->errorCode) {

                case UserIdentity::ERROR_EMAIL_INVALID:
                    $this->addError("username", Yii::t("UserModule.user", "Email is incorrect."));
                    break;
                case UserIdentity::ERROR_USERNAME_INVALID:
                    $this->addError("username", Yii::t("UserModule.user", "Username is incorrect."));
                    break;
                case UserIdentity::ERROR_STATUS_NOTACTIVE:
                    $this->addError("status", Yii::t("UserModule.user", "You account is not activated."));
                    break;
                case UserIdentity::ERROR_STATUS_BANNED:
                    $this->addError("status", Yii::t("UserModule.user", "You account is blocked."));
                    break;
                case UserIdentity::ERROR_PASSWORD_INVALID:
                    $this->addError("password", Yii::t("UserModule.user", "Password is incorrect."));
                    break;
                case UserIdentity::ERROR_NONE:
                    Yii::app()->user->id = $identity->id;
                    break;
            }
        }
    }

}



?>
